#!/bin/sh
#
# rc.savecore
#
# part of pfSense (https://www.pfsense.org)
# Copyright (c) 2004-2013 BSD Perimeter
# Copyright (c) 2013-2016 Electric Sheep Fencing
# Copyright (c) 2014-2023 Rubicon Communications, LLC (Netgate)
# All rights reserved.
#
# Based on src/etc/rc.d/savecore from FreeBSD
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

dumpdevs=`/sbin/dumpon -l | /usr/bin/tr ',' ' '`
dumpdev_fallback=`/bin/realpath -q /dev/dumpdev`
dumpdir='/var/crash'

if [ "${dumpdevs}" = '/dev/null' ] ; then
	if [ -c "${dumpdev_fallback}" ]; then
		dumpdevs=${dumpdev_fallback}
	else
		echo "No dump devices found.  Savecore not run."
		exit
	fi
fi

if [ ! -d "${dumpdir}" ]; then
	echo "Dump directory does not exist.  Savecore not run."
	exit
fi

for dev in ${dumpdevs} ; do
	# Some values may or may not already start with '/dev/' so make sure
	#   they are consistent.
	thisd=/dev/${dev#/dev/}

	# Ensure the target device is a valid choice
	if [ "${thisd}" = "/dev/null" -o ! -c "${thisd}" ] ; then
		continue
	fi

	echo -n "Checking dump device ${thisd} for crash dumps ... "
	if savecore -C "${thisd}" >/dev/null; then
		echo "found data, saving."
		savecore ${dumpdir} ${thisd}
	else
		echo "no crash dumps on ${thisd}."
	fi
done
